<template>
    <div class="app-container">
        <!-- 查询区域 -->
        <el-card class="search-card" v-show="showSearch">
            <el-form :model="queryParams">
                <el-row :gutter="20">
                    <el-col :span="7">
                        <el-form-item label="接收者ID">
                            <el-input v-model="queryParams.receiverId" placeholder="请输入接收者ID" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="7">
                        <el-form-item label="阅读状态">
                            <el-select v-model="queryParams.readStatus" placeholder="请选择阅读状态" clearable>
                                <el-option label="全部" value="" />
                                <el-option label="未读" :value="0" />
                                <el-option label="已读" :value="1" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="7">
                        <el-form-item label="消息状态">
                            <el-select v-model="queryParams.messageStatus" placeholder="请选择消息状态" clearable>
                                <el-option label="全部" value="" />
                                <el-option label="待发送" :value="0" />
                                <el-option label="已发送" :value="1" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="3" class="search-buttons">
                        <el-button type="primary" @click="handleQuery">查询</el-button>
                        <el-button @click="resetQuery">重置</el-button>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>

        <!-- 操作按钮区域 -->
        <el-card class="operation-card">
            <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                    <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
                </el-col>
                <el-button type="success" plain icon="Promotion" :disabled="!selectedRows.length"
                    @click="handleSendSelected">
                    发送选中
                </el-button>
                <el-button type="warning" plain icon="Reading" :disabled="!selectedRows.length"
                    @click="handleMarkAsRead">
                    标记已读
                </el-button>
                <el-col :span="1.5">
                    <el-button type="danger" plain icon="Delete" :disabled="!selectedRows.length"
                        @click="handleBatchDelete">删除</el-button>
                </el-col>
                <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>
            <el-table v-loading="loading" :data="messageList" @selection-change="handleSelectionChange"
                style="width: 100%">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column prop="inStationMessageId" label="消息ID" align="center" />
                <el-table-column prop="receiverId" label="接收者ID" align="center" />
                <el-table-column prop="messageTitle" label="消息标题" align="center" />
                <el-table-column prop="sendTime" label="发送时间" align="center" width="180">
                    <template #default="{ row }">
                        {{ formatTime(row.sendTime) }}
                    </template>
                </el-table-column>
                <el-table-column prop="messageStatus" label="发送状态" align="center">
                    <template #default="{ row }">
                        <el-tag :type="row.messageStatus === 1 ? 'success' : 'info'">
                            {{ row.messageStatus === 1 ? '已发送' : '待发送' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="readStatus" label="阅读状态" align="center">
                    <template #default="{ row }">
                        <el-tag :type="row.readStatus === 1 ? 'success' : 'danger'">
                            {{ row.readStatus === 1 ? '已读' : '未读' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="markStatus" label="标记状态" align="center">
                    <template #default="{ row }">
                        <el-tag :type="getMarkStatusTagType(row.markStatus)">
                            {{ getMarkStatusName(row.markStatus) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="350">
                    <template #default="{ row }">
                        <el-button type="text" icon="Edit" @click="handleEdit(row)">编辑</el-button>
                        <el-button type="text" icon="Notification" @click="handleMarkAsRead(row)">处理</el-button>
                        <el-button type="text" icon="Promotion" @click="handleSend(row)">发送</el-button>
                        <el-button type="text" icon="Delete" @click="handleDelete(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination">
                <el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
                    :total="total" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleQuery" @current-change="handleQuery" />
            </div>
        </el-card>

        <!-- 新增/编辑对话框 -->
        <el-dialog v-model="dialog.visible" :title="dialog.title" width="600px" @closed="resetForm">
            <el-form ref="messageForm" :model="form" :rules="rules" label-width="120px">
                <el-form-item label="消息ID" prop="inStationMessageId" v-if="dialog.isEdit">
                    <el-input v-model="form.inStationMessageId" disabled />
                </el-form-item>
                <el-form-item label="接收者ID" prop="receiverId">
                    <el-input-number v-model="form.receiverId" :min="1" placeholder="请输入接收者ID" />
                </el-form-item>
                <el-form-item label="消息标题" prop="messageTitle">
                    <el-input v-model="form.messageTitle" placeholder="请输入消息标题" />
                </el-form-item>
                <el-form-item label="消息内容" prop="messageContent">
                    <el-input v-model="form.messageContent" type="textarea" :rows="4" placeholder="请输入消息内容" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialog.visible = false">取消</el-button>
                <el-button type="primary" @click="submitForm">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete, Promotion, Reading } from '@element-plus/icons-vue'
import {
    listInStationMessage,
    getInStationMessage,
    addInStationMessage,
    updateInStationMessage,
    deleteInStationMessage,
    sendInStationMessage,
    markMessageAsRead
} from '@/api/basic/message/instation.js'

const showSearch = ref(true)

// 数据状态
const loading = ref(false)
const messageList = ref([])
const total = ref(0)
const selectedRows = ref([])
const messageForm = ref(null)

// 查询参数
const queryParams = reactive({
    pageNum: 1,
    pageSize: 10,
    receiverId: '',
    readStatus: '',
    messageStatus: ''
})

// 表单数据
const form = reactive({
    inStationMessageId: undefined,
    receiverId: '',
    messageTitle: '',
    messageContent: ''
})

// 对话框状态
const dialog = reactive({
    visible: false,
    title: '',
    isEdit: false
})

// 表单验证规则
const rules = reactive({
    receiverId: [
        { required: true, message: '请输入接收者ID', trigger: 'blur' },
        { type: 'number', message: '接收者ID必须为数字', trigger: 'blur' }
    ],
    messageTitle: [
        { required: true, message: '请输入消息标题', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在2到50个字符', trigger: 'blur' }
    ],
    messageContent: [
        { required: true, message: '请输入消息内容', trigger: 'blur' },
        { min: 5, message: '长度至少5个字符', trigger: 'blur' }
    ]
})

// 格式化时间
const formatTime = (time) => {
    if (!time) return ''
    return new Date(time).toLocaleString()
}

// 获取标记状态状态名称
const getMarkStatusName = (status) => {
    const statusMap = {
        '0': '待处理',
        '1': '已处理',
        '2': '未处理'
    }
    return statusMap[status] || '未知'
}

// 获取处理状态标签样式
const getMarkStatusTagType = (status) => {
    const typeMap = {
        '0': 'warning',
        '1': 'success',
        '2': 'danger'
    }
    return typeMap[status] || 'info'
}

// 获取消息列表
const getList = async () => {
    loading.value = true
    try {
        const res = await listInStationMessage(queryParams)
        messageList.value = res.rows || []
        total.value = res.total || 0
    } catch (error) {
        console.error('获取消息列表失败:', error)
        ElMessage.error('获取消息列表失败')
    } finally {
        loading.value = false
    }
}

// 查询处理
const handleQuery = () => {
    queryParams.pageNum = 1
    getList()
}

// 重置查询
const resetQuery = () => {
    queryParams.pageNum = 1
    queryParams.receiverId = ''
    queryParams.readStatus = ''
    queryParams.messageStatus = ''
    getList()
}

// 多选处理
const handleSelectionChange = (selection) => {
    selectedRows.value = selection.map(item => item.inStationMessageId)
}

// 新增消息
const handleAdd = () => {
    dialog.visible = true
    dialog.title = '新增站内消息'
    dialog.isEdit = false
}

// 编辑消息
const handleEdit = async (row) => {
    try {
        const res = await getInStationMessage(row.inStationMessageId)
        Object.assign(form, res.data)
        dialog.visible = true
        dialog.title = '编辑站内消息'
        dialog.isEdit = true
    } catch (error) {
        console.error('获取消息详情失败:', error)
        ElMessage.error('获取消息详情失败')
    }
}

// 发送消息
const handleSend = async (row) => {
    try {
        await sendInStationMessage(row.inStationMessageId)
        ElMessage.success('发送成功')
        getList()
    } catch (error) {
        console.error('发送失败:', error)
        ElMessage.error('发送失败')
    }
}

// 发送选中消息
const handleSendSelected = async () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请至少选择一条记录')
        return
    }

    try {
        for (const id of selectedRows.value) {
            await sendInStationMessage(id)
        }
        ElMessage.success('批量发送成功')
        getList()
    } catch (error) {
        console.error('批量发送失败:', error)
        ElMessage.error('批量发送失败')
    }
}

// 标记已读
const handleMarkAsRead = async (row) => {
    try {
        if (row.inStationMessageId) {
            await markMessageAsRead({ inStationMessageId: row.inStationMessageId, readStatus: 2 });
        } else {
            for (const id of selectedRows.value) {
                await markMessageAsRead({ inStationMessageId: id, readStatus: 1 })
            }
        }
        ElMessage.success(`标记${row ? '处理' : '已读'}成功`);
        getList()
    } catch (error) {
        console.error('标记已读失败:', error)
        ElMessage.error('标记已读失败')
    }
}

// 删除消息
const handleDelete = (row) => {
    ElMessageBox.confirm('确认删除该消息吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            await deleteInStationMessage(row.inStationMessageId)
            ElMessage.success('删除成功')
            getList()
        } catch (error) {
            console.error('删除失败:', error)
            ElMessage.error('删除失败')
        }
    }).catch(() => { })
}

// 批量删除
const handleBatchDelete = () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请至少选择一条记录')
        return
    }

    ElMessageBox.confirm(`确认删除选中的${selectedRows.value.length}条记录吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            await deleteInStationMessage(selectedRows.value.join(','))
            ElMessage.success('批量删除成功')
            getList()
        } catch (error) {
            console.error('批量删除失败:', error)
            ElMessage.error('批量删除失败')
        }
    }).catch(() => { })
}

// 重置表单
const resetForm = () => {
    if (messageForm.value) {
        messageForm.value.resetFields()
    }
    Object.assign(form, {
        inStationMessageId: undefined,
        receiverId: '',
        messageTitle: '',
        messageContent: ''
    })
}

// 提交表单
const submitForm = async () => {
    try {
        await messageForm.value.validate()

        if (dialog.isEdit) {
            await updateInStationMessage(form)
            ElMessage.success('修改成功')
        } else {
            await addInStationMessage(form)
            ElMessage.success('新增成功')
        }
        dialog.visible = false
        getList()
    } catch (error) {
        if (error && error.fields) {
            ElMessage.warning('请检查表单填写是否正确')
        } else {
            console.error('操作失败:', error)
            ElMessage.error('操作失败')
        }
    }
}

// 初始化
getList()
</script>

<style scoped>
.search-card {
    margin-bottom: 20px;
}

.search-buttons {
    text-align: right;
    padding-top: 5px;
}

.operation-card {
    margin-bottom: 20px;
}

.operation-buttons {
    display: flex;
    gap: 10px;
}

.search-card :deep(.el-form-item) {
    margin-bottom: 0px;
}

.pagination {
    margin-top: 20px;
    text-align: right;
}
</style>